package com.tianxin.workbao.workBao.Activity;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.google.android.material.snackbar.Snackbar;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.User;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.StatusBarCompat;
import com.tianxin.workbao.workBao.fragment.BaseFragment;
import com.tianxin.workbao.workBao.helper.GreenDaoHelper;
import com.tianxin.workbao.workBao.holder.SearchViewHolder;
import com.tianxin.workbao.workBao.utils.common.AlertUtils;
import com.tianxin.workbao.workBao.utils.common.BeansUtil;
import com.tianxin.workbao.workBao.utils.common.KeyBoardUtils;
import com.tianxin.workbao.workBao.utils.common.SPUtils;
import com.tianxin.workbao.workBao.utils.common.ScreenUtils;
import com.tianxin.workbao.workBao.utils.common.TimeUtils;
import com.tianxin.workbao.workBao.view.ExpandView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by hacker on 2017/6/8.
 */

public abstract class BaseActivity extends AppCompatActivity {
    public final String TAG = getClass().getName() + "------------->";
    public static BaseActivity activity;
    public Toolbar mToolbar;
    public String searchHint;
    public int searchTag;
    public List<String> mTabTitles;
    public List<BaseFragment> mFragments;
    public SearchViewHolder.OnSearchHandlerListener searchHandlerListener;
    private TimePickerDialog mTimePickerDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        activity = this;
        mTabTitles = new ArrayList<>();
        mFragments = new ArrayList<>();
    }

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        return super.onCreateView(name, context, attrs);
    }


    public abstract void initData();

    public abstract void initEvent();

    public abstract void bindView();

    @Override
    protected void onResume() {
        super.onResume();
        activity = this;
    }

    @Override
    protected void onPause() {
        super.onPause();
        activity = null;
    }


    /**
     * 状态栏的颜色
     * 子类可以通过复写这个方法来修改状态栏颜色
     *
     * @return ID
     */
    protected int getStatusColor() {
        if (SPUtils.getPrefBoolean(Constant.THEME_MODEL, false)) {
            return R.color.colorPrimaryDarkNight;
        } else {
            return R.color.colorPrimary;
        }
    }

    /**
     * 沉浸式模式
     *
     * @param isImg
     */

    public void initStatusBar(boolean isImg) {
        if (isImg == true) {
            StatusBarCompat.compat(this, Color.TRANSPARENT);
        } else {
            StatusBarCompat.compat(this, getStatusColor());
        }
        ;
    }

    public AlertUtils getSweetAlertDialog(Context context) {
        return new AlertUtils(context);
    }

    /**
     * format phone number
     *
     * @param input
     * @return
     */
    public static String formatPhoneNumber(String input) {
        if (Pattern.matches(Constant.MOBILE_REGEX, input)) {
            return input.substring(0, 3) + " " + input.substring(3, 7) + " " + input.substring(7, input.length());
        } else {
            return input;
        }
    }

    public static void saveUserSharedPreferences(JSONObject obj) {
        User user = null;
        try {
            user = BeansUtil.userToBean(obj.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        SPUtils.setPrefLong(Constant.CURRENT_USER_ID, user.getId());
        SPUtils.setPrefString(Constant.CURRENT_USER_GENDER, user.getSex());
        SPUtils.setPrefString(Constant.CURRENT_USER_USERNAME, user.getUsername());
        SPUtils.setPrefString(Constant.CURRENT_USER_NAME, user.getName());
        SPUtils.setPrefString(Constant.CURRENT_USER_PASSWORD, user.getPassword());
        SPUtils.setPrefString(Constant.CURRENT_USER_MOBILE, user.getMobiletel());
        SPUtils.setPrefString(Constant.CURRENT_USER_LOGIN_TIME, TimeUtils.parseDateTime(user.getLastlogintime()));
        SPUtils.setPrefInt(Constant.CURRENT_USER_LOGIN_num, user.getLoginnum() + 1);
        SPUtils.setPrefString(Constant.CURRENT_USER_HEADER, user.getHeadphoto());
        SPUtils.setPrefInt(Constant.CURRENT_USER_ORGID, user.getOrgid());
        SPUtils.setPrefString(Constant.CURRENT_USER_ORG_NAME, user.getOrgname());
        SPUtils.setPrefInt(Constant.CURRENT_USER_PORGID, user.getPorgid());
        SPUtils.setPrefString(Constant.CURRENT_USER_PORG_NAME, user.getPorgname());
        SPUtils.setPrefString(Constant.CURRENT_USER_APPTOKEN, user.getApptoken());
    }


    public void handleExpendView(ExpandView expandView, ImageView arrowImageView) {
        if (expandView.isExpand()) {
            expandView.collapse();
            arrowImageView.setImageResource(R.drawable.ic_arrow_drop_down_black_24dp);
        } else {
            expandView.expand();
            arrowImageView.setImageResource(R.drawable.ic_arrow_drop_up_black_24dp);
        }
    }

    //显示搜索框
    public PopupWindow mPopupWindow;
    public SearchViewHolder mSearchViewHolder;

    public void showSearchView(final Context context, SearchViewHolder.OnSearchHandlerListener listener) {
        final WindowManager.LayoutParams lp = getWindow().getAttributes();
        if (mSearchViewHolder != null) {
            mSearchViewHolder.setSeachListener(listener);
            mSearchViewHolder.setHint(searchHint);
        } else {
            mSearchViewHolder = new SearchViewHolder(context, listener, searchHint);
        }
        if (mPopupWindow == null) {
            mPopupWindow = new PopupWindow(mSearchViewHolder.getContentView(),
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT, true);
            mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            mPopupWindow.setFocusable(true);
            mPopupWindow.setOutsideTouchable(true);
            // 设置popWindow的显示和消失动画
            mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mSearchViewHolder.et_search_content.setText("");
                    KeyBoardUtils.closeKeyBord(mSearchViewHolder.et_search_content, context);
                    ValueAnimator animator = ValueAnimator.ofFloat(0.7f, 1f);
                    animator.setDuration(500);
                    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator valueAnimator) {
                            lp.alpha = (float) valueAnimator.getAnimatedValue();
                            lp.dimAmount = (float) valueAnimator.getAnimatedValue();
                            getWindow().setAttributes(lp);
                            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                        }
                    });
                    animator.start();
                }
            });
            mPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return false;
                }
            });
        } else {
            mPopupWindow.setContentView(mSearchViewHolder.getContentView());
        }
        KeyBoardUtils.openKeyBord(mSearchViewHolder.et_search_content, context);
        ValueAnimator animator = ValueAnimator.ofFloat(1f, 0.7f);
        animator.setDuration(500);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                lp.alpha = (float) valueAnimator.getAnimatedValue();
                lp.dimAmount = (float) valueAnimator.getAnimatedValue();
                getWindow().setAttributes(lp);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            }
        });
        mPopupWindow.showAtLocation(mToolbar, Gravity.NO_GRAVITY, 0, ScreenUtils.getStatusHeight(activity));
        animator.start();
    }

    //搜索接口
    public SearchViewHolder.OnSearchHandlerListener getSearchHandlerListener() {
        if (searchHandlerListener == null) {
            searchHandlerListener = new SearchViewHolder.OnSearchHandlerListener() {
                @Override
                public void onSearch(int code) {
                    switch (code) {
                        case SearchViewHolder.RESULT_SEARCH_EMPTY_KEYWORD:
                            Snackbar.make(getWindow().getDecorView(), R.string.keyword_is_empty, Snackbar.LENGTH_SHORT).show();
                            break;
                        case SearchViewHolder.RESULT_SEARCH_SEARCH:
                            String query = mSearchViewHolder.et_search_content.getText().toString();
                            mFragments.get(searchTag).search(query);
                            break;
                        case SearchViewHolder.RESULT_SEARCH_GO_SCAN:
                            break;
                        case SearchViewHolder.RESULT_SEARCH_CANCEL:
                            mPopupWindow.dismiss();
                            break;
                    }
                }
            };
        }
        return searchHandlerListener;
    }

    public void showToastMessage(Context context, String msg, int length) {
        if (length == 1) {
            Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * quit app To login activity
     */
    public void quitApp() {
        SPUtils.setPrefLong(Constant.CURRENT_USER_ID, 0);
        SPUtils.setPrefString(Constant.CURRENT_USER_NAME, null);
        SPUtils.setPrefString(Constant.CURRENT_USER_PASSWORD, null);
        startActivity(new Intent(this, LoginActivity.class));
        GreenDaoHelper.newInstance().getDaoSession().getRoleDao().deleteAll();
        GreenDaoHelper.newInstance().getDaoSession().getUserroleKeyDao().deleteAll();
        this.finish();
    }

    public com.jzxiang.pickerview.TimePickerDialog getTimePickerDialog(OnDateSetListener listener) {

        if (mTimePickerDialog == null) {
            mTimePickerDialog = new com.jzxiang.pickerview.TimePickerDialog.Builder()
                    .setCallBack(listener)
                    .setCancelStringId(getResources().getString(R.string.picker_cancel))
                    .setSureStringId(getResources().getString(R.string.picker_sure))
                    .setTitleStringId(getResources().getString(R.string.picker_title))
                    .setCyclic(false)
                    .setMinMillseconds(System.currentTimeMillis())
                    .setSelectorMillseconds(System.currentTimeMillis())
                    .setThemeColor(getResources().getColor(R.color.timepicker_dialog_bg))
                    .setType(Type.ALL)
                    .setWheelItemTextNormalColorId(getResources().getColor(R.color.timetimepicker_default_text_color))
                    .setWheelItemTextSelectorColorId(getResources().getColor(R.color.timepicker_toolbar_bg))
                    .setWheelItemTextSize(12)
                    .build();
        }
        return mTimePickerDialog;
    }
}

